<!--
 * @Author: panghu chenjh@datamargin.com
 * @Date: 2024-04-11 17:22:57
 * @LastEditors: panghu chenjh@datamargin.com
 * @LastEditTime: 2024-04-26 18:14:47
 * @FilePath: \zheye\src\views\login.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="login-page mx-auto p-3 w-330">
    <h5 class="my-4 text-center">登录到者也</h5>
    <ValidateForm @form-submit="onSubmitForm">
      <div class="mb-3">
        <label class="form-label">邮箱</label>
        <ValidateInput v-model="formData.email" :rules="emaiRules" placeholder="请输入邮箱"/>
      </div>
      <div class="mb-3">
        <label class="form-label">密码</label>
        <ValidateInput v-model="formData.password" :rules="passwordRules" type="password" placeholder="请输入密码"/>
      </div>
      <template #submit>
        <button type="button" class="btn btn-primary">登 录</button>
      </template>
    </ValidateForm>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import ValidateInput, { RulesType } from '@/components/ValidateInput.vue'
import ValidateForm from '@/components/ValidateForm.vue'
import CreateMessage from '@/components/createMessage'

export default defineComponent({
  name: 'LoginComp',
  components: { ValidateForm, ValidateInput },
  setup () {
    const timer = ref<null | number>(null)
    const store = useStore()
    const router = useRouter()
    const emaiRules: RulesType = [
      { type: 'required', message: '邮箱不能为空' },
      { type: 'email', message: '邮箱格式不对' }
    ]
    const passwordRules: RulesType = [
      { type: 'required', message: '密码不能为空' }
    ]
    const formData = reactive({
      email: '111@test.com',
      password: '111111'
    })
    const onSubmitForm = (value: boolean) => {
      if (value) {
        store.dispatch('loginAndGetUser', {
          email: formData.email,
          password: formData.password
        }).then(_ => {
          CreateMessage('登录成功，两秒后跳转首页', 'success')
          timer.value && clearTimeout(timer.value)
          timer.value = setTimeout(() => {
            router.push('/')
          }, 2000)
        }).catch(e => console.log(e))
      }
    }
    return {
      emaiRules,
      passwordRules,
      formData,
      onSubmitForm
    }
  }
})
</script>

<style scoped>

</style>
